Common.php
<?php
namespace Tlf\Lia;
class Common {
protected $lia;
public function __construct($lia){
$this->lia = $lia;
}
public function enable_markdown(){
$this->lia->schedule('RouteResolved',
[$this, 'convert_to_markdown']
);
}
public function enable_seo_parsing(){
$this->lia->schedule('RouteResolved',
[$this, 'parse_seo_content']
);
}
public function convert_to_markdown($route, $response){
$url = $response->request->url();
if (substr($url,-1)!='/')return;
$hasMarkdownNode = strpos($response->content, '<markdown>') !== false;
if (!$hasMarkdownNode)$response->content = '<markdown>'.$response->content.'</markdown>';
while(($start=strpos($response->content, '<markdown>'))!==false){
$tagLen = strlen('<markdown>');
$mdStart = $start + $tagLen;
$end = strpos($response->content, '</markdown>', $start);
$md = substr($response->content, $mdStart, $end-$mdStart);
$cmark = new \League\CommonMark\CommonMarkConverter();
$convertedToHtml = $cmark->convertToHtml($md);
$response->content = substr($response->content, 0,$start)
. $convertedToHtml
. substr($response->content, $end + strlen('</markdown>'));
}
if (!$hasMarkdownNode){
$response->content = '<section>' . $response->content . '</section>';
}
}
function parse_seo_content($route, $response){
$lia = $this->lia;
try {
$phtml = new \Taeluf\PHTML($response->content);
$h1 = $phtml->xpath('//h1')[0] ?? null;
if ($h1===null)return;
$lia->seoTitle($h1->textContent);
$p = $phtml->xpath('//p')[0];
$lia->seoDescription($p->textContent);
$img = $phtml->xpath('//img')[0]?? null;
if ($img!==null)$lia->seoImage($lia->urlWithDomain($img->src), $img->alt);
} catch (\Exception $e){
// just leave it be
}
}
/**
*
* This code is being used in one of my websites. I just haven't bothered to make this robust yet.
*/
// function add_breadcrumb($route, $response){
// // if (strlen($url)>7&&substr($url,0,7)=='/covid/' && ($_GET['action']??null) != 'print'){
// // $breadcrumb = '<small><a href="/covid/">Covid</a></small>';
// // $response->content = $breadcrumb." \n\n".$response->content;
// // } else if (strlen($url)>6&&substr($url,0,6)=='/foia/' && ($_GET['action']??null) != 'print'){
// // $breadcrumb = '<small><a href="/foia/">Foia</a></small>';
// // $response->content = $breadcrumb." \n\n".$response->content;
// // }
// }
}